<template>
  <view class="parkPayConfirmMm container">
    <view class="top">
      <view class="top_part" :style="'background-image: url('+parkInfo.imgInfo+');'" />
      <view class="part_info">
        <view class="palte_no">{{ parkInfo.plateNo }}</view>
        <view class="park_info_row"><text>车场名称：</text>{{ parkInfo.parkName }}</view>
        <view class="park_info_row"><text>入场时间：</text>{{ parkInfo.entryTime }}</view>
        <view class="park_info_row"><text>停车时长：</text>{{ parkInfo.elapsedTimeStr }}</view>
        <view class="park_info_row orange"><text>停车费用：</text>{{ parkInfo.totalAmount/100 }}元</view>
      </view>
      <view class="coupon_box_v">
        <view class="coupon_box">
          <view>停车券</view>
          <view class="coupon_box_right grey" @tap="coupon.coupon = true">
            <view :class="couponStyle" class="coupon_title">{{ couponTitle }}</view>
            <text class="iconfont icon-arrow-right grey" />
          </view>
        </view>
        <view class="coupon_box">
          <view>积分抵扣</view>
          <u-checkbox-group shape="circle" icon-size="16" size="24" active-color="red">
            <u-checkbox v-model="usePonitsFlag" :label="'-￥'+pointsDiscountAmount || ''" label-size="17" label-color="#fc4141" @change="changePoints" />
          </u-checkbox-group>
        </view>
        <view class="coupon_box">
          <view>微信支付</view>
          <view class="red">￥{{ finalMoney }}</view>
        </view>
        <view class="rule grey">
          <view>当前积分:{{ parkingRule.pointsBalance }}</view>
          <view>{{ parkingRule.description }}</view>
          <view v-if="usePonitsFlag" class="red">扣除积分: - {{ usedPoints }}</view>
        </view>
      </view>
    </view>

    <view class="pay_btn" @tap="payComfirm">
      <view>确认出场 </view>
      <u-count-down :time="5 * 60 * 1000" format="HH:mm:ss" @finish="countDownFinish" @change="countDownChange">
        <view class="time">
          {{ countDownTime.minutes }}分{{ countDownTime.seconds }}秒
        </view>
      </u-count-down>
    </view>

    <u-modal :show="payTipShow" title="支付提示" confirm-text="继续支付" show-cancel-button show-confirm-button :content="payTipContent" @confirm="pay" @cancel="payTipShow=false" />
    <couponList-window :coupon="coupon" @ChangCouponsClone="coupon.coupon = false" @ChangCoupons="ChangCoupons" />
  </view>
</template>
<script>
import couponListWindow from '@/components/couponListWindow/couponListWindow'
const util = require('@/utils/util.js')
import {
  parkingCouponRule,
  mmPointsCouponParkingMyParkingCouponList,
  wxPay2UnifiedOrder,
  mmParkingPayParkingFee,
  mmParkingPayRecordReporting
} from '@/api/api1'
export default {
  components: {
    couponListWindow
  },
  props: {
    parkInfo: {
      type: Object,
      default: () => { }
    }
  },
  data() {
    return {
      coupon: {
        coupon: false, // 控制弹窗
        list: [],
        statusTile: '立即使用'
      }, // 优惠券组件
      couponId: 0, // 优惠券id
      couponTitle: '请选择', // 优惠券
      couponDiscountAmount: 0, // 优惠券-抵扣金额

      usePonitsFlag: false, // 是否使用积分
      usedPoints: 0, // 使用积分总数
      pointsDiscountAmount: 0, // 积分-抵扣金额

      parkingRule: {}, // 停车兑换规则

      countDownTime: {},
      payTipShow: false,
      payTipContent: ''
    }
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo
    },
    // 最终金额
    finalMoney() {
      var x = util.accSub(util.accSub(this.parkInfo.payMoney, this.couponDiscountAmount), this.pointsDiscountAmount)
      return x <= 0 ? 0 : x
    },
    // 总优惠金额
    discountAmount() {
      var x = util.accAdd(this.couponDiscountAmount, this.pointsDiscountAmount)
      return x <= 0 ? 0 : x
    },
    couponStyle() {
      return this.coupon.list.length > 0 ? 'red' : ''
    }
  },
  mounted() {
    this.init()
  },
  onReachBottom() {
  },
  methods: {
    payComfirm() {
      // 如果有券 有积分的时候，提示
      if (this.finalMoney === 0) {
        this.pay()
        return
      } else if (this.couponId === 0 && this.coupon.list.length > 0) {
        this.payTipShow = true
        this.payTipContent = '当前有' + this.coupon.list.length + '张可使用券，是否继续支付'
        return
      } else if (!this.usePonitsFlag && this.parkingRule.pointsBalance > this.parkingRule.redeemPoints) {
        this.payTipShow = true
        this.payTipContent = '当前有' + this.parkingRule.pointsBalance + '积分可用，是否继续支付'
        return
      }
      this.pay()
    },
    countDownChange(e) {
      this.countDownTime = e
    },
    countDownFinish() {
      util.bak()
    },
    async init() {
      var that = this

      uni.showLoading({ title: '加载停车规则' })
      // 获取会员-抵扣规则
      await parkingCouponRule({ cardNo: that.userInfo.cardNo }).then(res => {
        console.log('美美停车规则', res)
        that.parkingRule = res.data
      })

      // 获取当前金额可用优惠券
      await mmPointsCouponParkingMyParkingCouponList({ cardNo: that.userInfo.cardNo }).then(res => {
        console.info('我的停车券', res)
        that.coupon.list = res.data
        that.openType = 1
        if (res.data.length > 0) {
          that.couponTitle = res.data.length + '张优惠券可选'
        } else {
          that.couponTitle = '暂无优惠券'
        }
      })
      uni.hideLoading()
    },
    // 使用积分抵扣，计算扣减积分
    changePoints(e) {
      this.usePonitsFlag = e
      this.caculateIntegral()
    },
    caculateIntegral() {
      // 如果 没有开启积分抵扣 || 积分余额=0 || 券抵扣金额 > 停车费
      if (!this.usePonitsFlag ||
        this.parkingRule.pointsBalance === 0 ||
        this.couponDiscountAmount >= this.parkInfo.payMoney
      ) {
        // 使用积分=0
        this.usedPoints = 0
        // 积分抵扣金额=0
        this.pointsDiscountAmount = 0
        return
      }
      // 如果 兑换积分=0 或 兑换金额=0 或 兑换积分 > 积分余额
      if (this.parkingRule.redeemPoints === 0 ||
        this.parkingRule.redeemMoney === 0 ||
        this.parkingRule.redeemPoints > this.parkingRule.pointsBalance
      ) return

      // 需要使用的倍数(向上取整) = (停车费-券抵扣金额) / 兑换金额
      var z = Math.ceil(util.accDiv(util.accSub(this.parkInfo.payMoney, this.couponDiscountAmount), this.parkingRule.redeemMoney))
      // 可以使用的倍数(向下取整) = 积分余额 / 兑换积分
      var i = parseInt(util.accDiv(this.parkingRule.pointsBalance, this.parkingRule.redeemPoints))
      // 不能完全抵扣，使用i，可以兑换几次就用几次
      if (z > i) {
        // 使用积分
        this.usedPoints = util.accMul(i, this.parkingRule.redeemPoints)
        // 积分抵扣金额
        this.pointsDiscountAmount = util.accMul(i, this.parkingRule.redeemMoney)
      } else {
        // 可以完全抵扣，使用z
        // 使用积分
        this.usedPoints = util.accMul(z, this.parkingRule.redeemPoints)
        // 积分抵扣金额
        this.pointsDiscountAmount = util.accMul(z, this.parkingRule.redeemMoney)
      }
    },
    // 处理点击优惠券后的事件
    ChangCoupons(e) {
      var index = e
      var list = this.coupon.list
      var couponTitle = '暂无优惠券'
      var couponId = 0
      var couponDiscountAmount = 0
      if (this.coupon.list.length > 0) {
        couponTitle = this.coupon.list.length + '张优惠券可选'
      }
      for (var i = 0, len = list.length; i < len; i++) {
        if (i !== index) {
          list[i].use_title = ''
          list[i].is_use = 0
        }
      }
      if (list[index].is_use) {
        // 不使用优惠券
        list[index].use_title = ''
        list[index].is_use = 0
      } else {
        // 使用优惠券
        list[index].use_title = '不使用'
        list[index].is_use = 1
        couponTitle = '-￥' + list[index].redeemMoney
        couponId = list[index].id
        if (list[index].redeemMoney > this.finalMoney) {
          couponDiscountAmount = this.finalMoney
        } else {
          couponDiscountAmount = list[index].redeemMoney
        }
      }
      this.couponTitle = couponTitle
      this.couponId = couponId
      this.coupon.coupon = false
      this.coupon.list = list
      this.couponDiscountAmount = couponDiscountAmount
      this.caculateIntegral()
    },
    async pay() {
      this.payTipShow = false
      uni.showLoading({
        title: '支付中...'
      })
      var that = this

      // 支付
      const payNo = that.parkInfo.orderNo// 停车单号
      const finalMoney = that.finalMoney// 支付金额
      const discountAmount = that.discountAmount// 总优惠金额
      const cardNo = that.userInfo.cardNo// 卡号
      const storeNo = '201'
      const phone = that.userInfo.phone// 手机号
      const openId = that.userInfo.miniOpenid
      const body = '停车支付'

      var params = {}
      // 券核销请求参数
      if (that.couponId !== 0) {
        params.proParkingCouponWriteOff = {
          couponId: that.couponId,
          couponRedeemAmount: that.couponDiscountAmount,
          storeNo: storeNo
        }
      }
      // 积分抵扣请求参数
      if (that.usePonitsFlag && that.usedPoints > 0) {
        params.parkingPointsPayDiscount = {
          cardNo: cardNo,
          discountPoints: that.usedPoints,
          storeNo: storeNo,
          memo: '积分抵扣停车费'
        }
      }

      // 券核销 积分抵扣 支付上报 一个事务下执行
      if (that.finalMoney === 0) {
        if (that.couponId !== 0 || (that.usePonitsFlag && that.usedPoints > 0)) {
          params.payParkingFee = that.parkingReportBean()
          await mmParkingPayRecordReporting(params).then(res => {
            uni.hideLoading()
            util.Open('成功', '支付完成，30分钟内离场', () => {
              uni.$u.route({ type: 'redirect', url: '/pages/parkBill/parkBill' })
            })
          })
        }
        // 如果没有用券，积分，最后还支付0元（美美没有这个情况 暂时不处理）
        return
      }

      var unifiedOrderParam = {
        outTradeNo: payNo, // 商户订单号
        deviceInfo: storeNo, // 门店号或收银设备ID
        body: body, // 商品描述
        totalFee: util.accMul(finalMoney, 100), // 标价金额(单位为分)
        openId: openId
      }
      var requestPaymentParam = null
      await wxPay2UnifiedOrder(unifiedOrderParam).then(res => {
        console.info('统一下单返回：', res)
        if (!res) {
          return wx.hideLoading()
        }
        requestPaymentParam = res.data.signObj
      })

      var attachData = JSON.parse(JSON.stringify(params))
      attachData.payParkingFee = that.parkingReportBean()

      var orderParam = {
        orderNo: payNo,
        money: finalMoney,
        discountAmout: discountAmount,
        finalMoney: finalMoney,
        mkt: storeNo,
        phone: phone,
        cardNo: cardNo,
        orderType: 'ORDER_PARK',
        remark: that.parkInfo.plateNo,
        attach: JSON.stringify(attachData)
      }
      console.info('保存订单参数：', orderParam)
      params.order = orderParam

      // 保存订单，积分扣减 券核销
      await mmParkingPayRecordReporting(params)

      // 唤起支付
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: requestPaymentParam.timeStamp,
        nonceStr: requestPaymentParam.nonceStr,
        package: requestPaymentParam.packageObj,
        signType: requestPaymentParam.signType,
        paySign: requestPaymentParam.paySign,
        success(res) {
          wx.hideLoading()
          console.log('success:' + JSON.stringify(res))
          console.log('微信支付成功')
          util.Open('成功', '支付完成，30分钟内离场', function() {
            uni.redirectTo({
              url: '/pages/parking/parkBill/index'
            })
          })
        },
        fail(err) {
          wx.hideLoading()
          console.log('fail:' + JSON.stringify(err))
          console.log('微信支付失败')
        }
      })
    },
    /**
   * 缴费上报
   * type 1:全额支付 2：积分支付 3：券支付 4：积分+券支付
   */
    parkingReportBean() {
      const that = this
      let type = 1
      if (that.couponId !== 0 && that.usePonitsFlag && that.usedPoints > 0) {
        type = 4
      } else if (that.couponId !== 0) {
        type = 3
      } else if (that.usePonitsFlag && that.usedPoints > 0) {
        type = 2
      }
      const param = {
        orderNo: that.parkInfo.orderNo,
        payableAmount: that.parkInfo.payable,
        freeMoney: that.discountAmount,
        freeTime: 0,
        plateNo: that.parkInfo.plateNo,
        entryTime: that.parkInfo.entryTime,
        payMethod: 4 // 付款方式
      }
      if (type === 2) {
        param.freeDetail = JSON.stringify([{
          money: that.discountAmount, // 减免金额 单位：分
          time: 0, // 减免时间 单位：秒
          code: that.userInfo.cardNo, // 会员id、抵扣券编号、购物小票号
          type: 0, // 抵扣来源：0:积分抵扣（对应支付方式1013） 1:抵扣券(对应支付方式1010) 2:购物小票(对应支付方式1014),3:会员减免(对应支付方式1012)等
          freeName: '停车费积分抵扣' + that.discountAmount / 100 + '元'
        }])
        param.payMethod = 1013
      } else if (type === 3) {
        param.freeDetail = JSON.stringify([{
          money: that.discountAmount, // 减免金额 单位：分
          time: 0, // 减免时间 单位：秒
          code: that.userInfo.cardNo + that.couponId, // 会员id、抵扣券编号、购物小票号
          type: 1, // 抵扣来源：0:积分抵扣（对应支付方式1013） 1:抵扣券(对应支付方式1010) 2:购物小票(对应支付方式1014),3:会员减免(对应支付方式1012)等
          freeName: '停车费券抵扣' + that.discountAmount / 100 + '元'
        }])
        param.payMethod = 1010
      } else if (type === 4) {
        param.freeDetail = JSON.stringify([{
          money: that.pointsDiscountAmount * 100, // 减免金额 单位：分
          time: 0, // 减免时间 单位：秒
          code: that.userInfo.cardNo, // 会员id、抵扣券编号、购物小票号
          type: 0, // 抵扣来源：0:积分抵扣（对应支付方式1013） 1:抵扣券(对应支付方式1010) 2:购物小票(对应支付方式1014),3:会员减免(对应支付方式1012)等
          freeName: '停车费积分加券抵扣' + that.pointsDiscountAmount + '元'
        }, {
          money: that.couponDiscountAmount * 100, // 减免金额 单位：分
          time: 0, // 减免时间 单位：秒
          code: that.userInfo.cardNo + that.couponId, // 会员id、抵扣券编号、购物小票号
          type: 1, // 抵扣来源：0:积分抵扣（对应支付方式1013） 1:抵扣券(对应支付方式1010) 2:购物小票(对应支付方式1014),3:会员减免(对应支付方式1012)等
          freeName: '停车费券抵扣' + that.couponDiscountAmount + '元'
        }])
        param.payMethod = 1010
      }
      return param
    }
  }
}
</script>

<style lang="scss" scoped>
.parkPayConfirmMm {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  max-width: 750rpx;
  margin: auto;
  .top {
    height: calc(100% - 100rpx);
    overflow-y: scroll;
    -webkit-overflow-scrolling: touch;
    position: relative;
    margin: auto;
  }
  .pay_btn {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    max-width: 750rpx;
    height: 100rpx;
    @include flex-center;
    font-size: 42rpx;
    color: white;
    background-color: #d68e1f;
    box-shadow: 12px 12px 50px #7d7c7c;

    .time {
      font-size: 26rpx;
      border: 1rpx #fff solid;
      padding: 6rpx;
      border-radius: 10rpx;
      margin-left: 10rpx;
      position: fixed;
      bottom: 22rpx;
    }
  }
}

.top_part {
  width: 100%;
  height: 270rpx;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.part_info {
  background-color: #fff;
  width: 90%;
  margin: -50rpx auto 0;
  border-radius: 10rpx;
  .palte_no {
    font-size: 32rpx;
    text-align: center;
    padding: 20rpx 0;
    font-weight: bold;
    border-bottom: 1rpx solid #e4e2e2;
  }
  .park_info_row {
    font-size: 26rpx;
    line-height: 60rpx;
    margin-left: 20rpx;
    text {
      color: #909090;
    }
  }
}

.coupon_box_v {
  width: 90%;
  @include flex-space-between(column);
  margin: auto;
  .coupon_box {
    @include flex-space-between;
    width: 100%;
    height: 100rpx;
    line-height: 100rpx;
    font-size: 30rpx;
    border-bottom: 1px solid #e8e8e8;
    .coupon_box_right {
      @include flex-space-between;
      .coupon_title {
        width: 280rpx;
        text-align: end;
      }
    }
  }
  .rule {
    width: 100%;
    @include flex-left(column);
    gap: 40rpx;
    align-items: flex-end;
  }
}

.grey {
  color: #909090;
}
.orange {
  color: #d68e1f;
}
.red {
  color: #fc4141 !important;
}
</style>
